<!--
/**
 * 课程教学总结审核列表组件
 * 
 * 功能说明：
 * 1. 显示待审核的教学总结列表
 * 2. 支持按课程名称、教师、学期等条件筛选
 * 3. 提供查看详情、审核操作等功能
 * 4. 根据用户角色显示不同的待审核内容：
 *    - 教研室主任：显示待教研室审核的总结
 *    - 部系主任：显示待部系审核的总结
 *    - 管理员：显示所有待审核的总结
 * 
 * 数据交互：
 * 1. 初始化时从后端获取待审核总结列表 /api/kcjxzj/pending
 * 2. 过滤条件变化时重新获取数据
 * 3. 审核操作调用对应的审核接口
 * 
 * 组件依赖：
 * - element-ui 组件库
 * - api/kcjxzj.js 接口封装
 * - vuex 用户状态管理
 */
-->
<template>
  <div class="admin-page summary-audit-list">
    <div class="page-header">
      <h1>待审核总结列表</h1>
    </div>
    
    <el-card class="table-card">
      <div class="filter-container">
        <el-form :inline="true" class="filter-form">
          <el-form-item label="学期">
            <el-select v-model="filters.termId" placeholder="请选择学期" clearable style="width: 250px;">
              <el-option v-for="term in terms" :key="term.id" :label="term.name" :value="term.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="课程名称">
            <el-input v-model="filters.courseName" placeholder="请输入课程名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="教师">
            <el-input v-model="filters.teacherName" placeholder="请输入教师姓名" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchSummaries">搜索</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-table
        v-loading="loading"
        :data="pendingSummaries"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="courseName" label="课程名称" min-width="120" resizable>
          <template #default="scope">
            {{ scope.row.courseName || (scope.row.course && scope.row.course.name) || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="teacherName" label="教师" min-width="100" resizable>
          <template #default="scope">
            {{ scope.row.teacherName || (scope.row.teacher && scope.row.teacher.name) || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="termName" label="学期" min-width="100" resizable>
          <template #default="scope">
            {{ scope.row.termName || (scope.row.term && scope.row.term.name) || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="提交时间" min-width="180" resizable>
          <template #default="scope">
            {{ formatDate(scope.row.createdTime || scope.row.createDate || scope.row.commitDate) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="100" resizable>
          <template #default="scope">
            <el-tag type="warning">待审核</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="重复度检测" min-width="150" resizable>
          <template #default="scope">
            <el-tooltip content="查看重复度详情" placement="top">
              <el-button type="info" size="small" plain @click="showDuplicationInfo(scope.row.id)">
                <el-icon><Document /></el-icon> 检测
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" min-width="150" resizable>
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewSummary(scope.row.id)">查看</el-button>
            <el-button type="success" size="small" @click="auditSummary(scope.row.id)">审核</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 添加详情对话框 -->
    <SummaryViewDialog
      v-model:visible="summaryDialogVisible"
      :summaryId="currentSummaryId"
      @close="handleDialogClose"
    />
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getPendingAuditKcjxzj } from '@/api/course-teaching-summary'
import { termApi } from '@/api/base-data'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import SummaryViewDialog from '@/components/common/SummaryViewDialog.vue' // 引入详情对话框组件

export default {
  components: {
    SummaryViewDialog,
    Document
  },
  setup() {
    const router = useRouter()
    const userStore = useUserStore()
    
    // 详情对话框相关
    const summaryDialogVisible = ref(false)
    const currentSummaryId = ref(null)
    
    // 列表数据
    const allSummaries = ref([])
    const loading = ref(false)
    const terms = ref([])
    
    // 分页相关
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    // 筛选条件
    const filters = reactive({
      courseName: '',
      teacherName: '',
      termId: ''
    })
    
    // 根据筛选条件和分页获取待审核的总结
    const pendingSummaries = computed(() => {
      // 后端已经根据用户权限返回了正确的待审核数据，前端只需要应用搜索筛选
      let filtered = allSummaries.value
      
      // 应用筛选条件
      if (filters.courseName) {
        filtered = filtered.filter(summary => {
          const courseName = summary.courseName || (summary.course && summary.course.name) || ''
          return courseName.includes(filters.courseName)
        })
      }
      
      if (filters.teacherName) {
        filtered = filtered.filter(summary => {
          const teacherName = summary.teacherName || (summary.teacher && summary.teacher.name) || ''
          return teacherName.includes(filters.teacherName)
        })
      }
      
      if (filters.termId) {
        filtered = filtered.filter(summary => 
          summary.termId === filters.termId
        )
      }
      
      // 更新总数
      total.value = filtered.length
      
      // 返回当前页的数据
      const startIndex = (currentPage.value - 1) * pageSize.value
      return filtered.slice(startIndex, startIndex + pageSize.value)
    })
    
    
    // 获取总结列表
    const fetchSummaries = async () => {
      loading.value = true
      try {
        // 使用新的专门的待审核API，后端已经做了权限过滤
        allSummaries.value = await getPendingAuditKcjxzj()
      } catch (error) {
        ElMessage.error('获取待审核总结列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 获取当前学期并设置为默认值
    const getCurrentTerm = (terms) => {
      // 查找标记为当前学期的记录
      const currentTerm = terms.find(term => term.isCurrent === true || term.is_current === true);
      
      // 如果没有找到当前学期，返回null（不设置默认值）
      if (!currentTerm && terms.length > 0) {
      }
      
      return currentTerm || null;
    };

    // 获取基础数据
    const fetchBaseData = async () => {
      try {
        terms.value = await termApi.getAllTerms()
        
        // 设置当前学期为默认值
        const currentTerm = getCurrentTerm(terms.value);
        if (currentTerm) {
          filters.termId = currentTerm.id;
        }
      } catch (error) {
      }
    }
    
    // 搜索总结
    const searchSummaries = () => {
      currentPage.value = 1
      // 过滤逻辑已在 computed 中实现
    }
    
    // 重置筛选条件
    const resetFilters = () => {
      filters.courseName = ''
      filters.teacherName = ''
      filters.termId = ''
      currentPage.value = 1
    }
    
    // 处理页码变化
    const handlePageChange = (page) => {
      currentPage.value = page
    }
    
    // 查看总结详情
    const viewSummary = (id) => {
      if (!id) {
        ElMessage.warning('总结ID无效，无法查看详情');
        return;
      }
      // 改为使用详情对话框查看而不是跳转到单独页面
      currentSummaryId.value = id;
      summaryDialogVisible.value = true;
    }
    
    // 处理对话框关闭
    const handleDialogClose = () => {
      // 对话框关闭后的处理
      currentSummaryId.value = null;
      summaryDialogVisible.value = false;
      
      // 可以选择性地刷新列表数据
      // fetchSummaries();
    }
    
    // 审核总结
    const auditSummary = (id) => {
      router.push(`/kcjxzj/summary-audit/${id}`)
    }
    
    // 显示重复度检测信息
    const showDuplicationInfo = async (summaryId) => {
      try {
        // 直接跳转到审核页面，在那里可以看到重复度检测结果
        router.push(`/kcjxzj/summary-audit/${summaryId}`)
      } catch (error) {
        ElMessage.error('查看重复度信息失败')
      }
    }
    
    // 日期格式化
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    onMounted(async () => {
      // 先获取基础数据，设置默认学期
      await fetchBaseData();
      // 然后获取总结数据（会使用默认学期过滤）
      await fetchSummaries();
    })
    
    return {
      pendingSummaries,
      loading,
      terms,
      filters,
      currentPage,
      pageSize,
      total,
      searchSummaries,
      resetFilters,
      handlePageChange,
      viewSummary,
      auditSummary,
      showDuplicationInfo,
      formatDate,
      // 添加对话框相关属性
      summaryDialogVisible,
      currentSummaryId,
      handleDialogClose
    }
  }
}
</script>

<style scoped>
.summary-audit-list {
  padding: 0;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.table-card {
  margin-bottom: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
